package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class ProjectInterceptor implements HandlerInterceptor {
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("employee") != null) {

            long empId = (long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            return true;
        }
        //判断登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("user") != null) {

            long userId = (long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            return true;
        }
        //如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
